import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)


class infrared(object):
    def __init__(self):

        self.GPIO_TRIGGER = 5
        self.GPIO_ECHO = 6

        GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(self.GPIO_ECHO, GPIO.IN)


    def DistMeasure(self):
        stop = 0
        start = 0
        distance = 0
        GPIO.output(self.GPIO_TRIGGER, False)
        time.sleep(0.5)
        GPIO.output(self.GPIO_TRIGGER, True)
        time.sleep(0.00001)
        GPIO.output(self.GPIO_TRIGGER, False)
        start = time.time()

        while GPIO.input(self.GPIO_ECHO) == 0:
            start = time.time()
        while GPIO.input(self.GPIO_ECHO) == 1:
            stop = time.time()
        if stop != 0 and start != 0:
            elapsed = stop - start
            distance = elapsed * 34300
            distance = distance / 2
        return distance


if __name__ == '__main__':
    try:
        car = infrared()
        while True:
            dist = car.DistMeasure()
            print("Measured Distance = {:.2f} cm".format(dist))
            time.sleep(1)

        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Measurement stopped by User")
        GPIO.cleanup()
